﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.Messages;
using SharedLib.MessageFramework;
using System.Text.RegularExpressions;
using System.Reflection;
using Tracy.BasicServices;

namespace Tracy.Handlers
{
    public class VersionCheckHandler : TaskMessageHandler
    {
        protected override void ProcessMessage(Messages.TaskMessage msg)
        {
            TracyFacade.Instance.MessageDispatcher.EnqueueMessage(new GetDataFromURLMessage(this, new MessageData<string>("http://tracy.codeplex.com/"), new MessageCallback(this.OnHtmlRetrieved), "GetDataFromURLHandler_VeryCD"));
        }

        private void OnHtmlRetrieved(IAppMessage msg)
        {
            if (msg != null && msg is GetDataFromURLMessage && !msg.CancelFlag)
            {
                if (msg.Exception == null)
                {
                    byte[] data = msg.Result as byte[];
                    string html = Encoding.UTF8.GetString(data);

                    Regex regex = new Regex("<td id=\"ReleaseName\" class=\"ActivityData\">.*</td>");
                    Match m = regex.Match(html);
                    if (m.Success)
                    {
                        string value = m.Value;
                        value = value.Substring(42, value.Length - 47).Replace("&#40;", "(").Replace("&#41;", ")");
                        if (value != AssemblyTitle)
                        {
                            TracyFacade.Instance.MessageDispatcher.NotifyUI(msg, NotifyUIEventArgs.NEW_VERSION_FOUND, value);
                        }
                    }
                }
            }
        }

        public string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().CodeBase);
            }
        }
    }
}
